package br.com.findme.findmeserver.controle;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import br.com.findme.findmeserver.dao.HibernateUtils;
import br.com.findme.findmeserver.entidade.Usuario;
import br.com.findme.findmeserver.mensagem.Mensagem;
import br.com.findme.findmeserver.utils.SenhaUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Servlet implementation class AlterarContaServlet
 */
public class AlterarContaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AlterarContaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doProcess(request, response);
	}
	
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Mensagem m = null;
		
		try {
			String pId = request.getParameter("id");
			String pNome = request.getParameter("nome");
			String pEmail = request.getParameter("email");
			String pFone = request.getParameter("fone");
			String pSenha = request.getParameter("senha");
				
			
		Session session = HibernateUtils.openSession();
		
		Criteria c = session.createCriteria(Usuario.class);
		c.add(Restrictions.and(
				Restrictions.eq("email", pEmail),
				Restrictions.not(Restrictions.eq("id", Integer.parseInt(pId)))
			)
		);
		
		
		List usuarios = c.list();
		
		if(usuarios.isEmpty()){			
			c = session.createCriteria(Usuario.class);
			c.add(Restrictions.eq("id", Integer.parseInt(pId)));
			Usuario usuario = (Usuario) c.uniqueResult();				
			if(pNome != null)
				usuario.setNome(pNome);
			if(pEmail != null)
				usuario.setEmail(pEmail);
			if(pSenha != null)
				usuario.setSenha(SenhaUtils.encodeMD5(pSenha));
			if(pFone != null)
				usuario.setFone(pFone);
			
			session.update(usuario);
			session.flush();
			m = new Mensagem(Mensagem.STATUS_SUCESSO, "Conta atualizado com sucesso.",usuario);
		}else{
			m = new Mensagem(Mensagem.STATUS_FALSO, "E-mail já cadastrado.");	
		}			
	} catch (Exception e) {
		m = new Mensagem(Mensagem.STATUS_ERRO, "Não foi possível atualizar a conta, por favor tente mais tarde.");			
	}
	
	PrintWriter pw = response.getWriter();
	
	GsonBuilder gb = new GsonBuilder();
	Gson gson = gb.registerTypeAdapter(Usuario.class, Usuario.toJSON()).create();
	String retorno = m.toString(gson);
	pw.append(retorno);
	
		
	}

}
